<template>
  <div>
    <a-card :bordered="false" class="mb-3">
      <div class="flex justify-between">
        <a-button @click="add" type="primary">{{ t["新增"] }}</a-button>
        <div class="flex">
          <div class="flex gap-2">
            <a-input-search
              v-model="query.name"
              search-button
              :button-text="t['搜索']"
              @click="search"
              @keydown.enter="search"
              allow-clear
            />
          </div>
          <a-divider direction="vertical" class="h-full"></a-divider>
          <XDelete :disabled="selectedKeys.length <= 0" @ok="deleteItem" />
        </div>
      </div>
    </a-card>
    <a-card :bordered="false">
      <a-table
        v-bind="comTableConfig"
        v-model:selectedKeys="selectedKeys"
        size="medium"
        :bordered="false"
        page-position="bottom"
        :columns="translateColumns(columns)"
        :data="tableData"
        :row-selection="rowSelection"
        row-key="id"
        :pagination="{
          pageSize: query.pageSize,
          total: query.total,
          current: query.pageNum,
          showJumper: true,
          showPageSize: true,
          showTotal: true
        }"
        @page-size-change="pageSizeChange"
        @filter-change="filterChange"
        @page-change="pageChange"
      >
        <template #type="{ record }">
          <a-tag>
            {{ getType(record.type)?.label }}
          </a-tag>
        </template>
        <template #status="{ record }">
          <a-switch
            :model-value="record.status === '0'"
            checked-color="#47976Caa"
            unchecked-color="#FF5400aa"
            disabled
          ></a-switch>
        </template>
        <template #actions="{ record }">
          <div class="flex gap-2 justify-center">
            <a-link @click="editItem(record)">
              {{ t["编辑"] }}
            </a-link>
            <XDelete status="danger" @ok="deleteItem(record.id)">
              {{ t["删除"] }}
            </XDelete>
          </div>
        </template>
      </a-table>
    </a-card>

    <CreateScheduled v-if="form.visible" @on-close="form.visible = false"></CreateScheduled>
  </div>
</template>

<script setup lang="ts">
import { delJobs, jobsList } from "@/api/service/scheduled/scheduled";
import { Scheduled, ScheduledDetails } from "@/api/service/scheduled/type";
import { QueueItem } from "@/api/service/sendqueue/types";
import useTableConfig from "@/hook/useTableConfig";

import { IQuery } from "@/interface/IAxios";
import { useEventBus } from "@vueuse/core";

import { form, getType, productKeys, resetForm } from ".";

import { columns } from "./columns";
import CreateScheduled from "./create/create-scheduled.vue";

const bus = useEventBus("refresh");
const { rowSelection, comTableConfig } = useTableConfig(columns);
const tableData = ref([] as Array<QueueItem>);
const t = translate("公共模块");
const selectedKeys = ref<string[]>([]);
const loading = ref(true);

const query = ref<IQuery>({
  name: "",
  pageNum: 1,
  pageSize: 30,
  total: 10,
  orderByColumn: "create_time",
  isAsc: "desc"
});

const getList = async () => {
  loading.value = true;
  const { rows, total } = await jobsList(query.value);
  tableData.value = rows;
  query.value.total = total;
  loading.value = false;
};
bus.on(() => {
  getList();
});
onMounted(() => {
  getList();
});

function pageChange(index: number) {
  query.value.pageNum = index;
  getList();
}

const editItem = (item: Scheduled) => {
  resetForm();
  form.value.name = item.name;
  form.value.id = item.id;
  form.value.type = item.type;
  form.value.startTime = item.start;

  form.value.endTime = item.stop;
  form.value.rangeTime = [item.start, item.stop];

  form.value.visible = true;
  form.value.deptId = item.deptId;
  form.value.status = item.status;

  const details: ScheduledDetails = JSON.parse(item.details);
  form.value.template = details.template as any;
  productKeys.value = details.goods;
  form.value.fields = details.fields.map((e: any) => {
    if (e.type === 0) {
      e.value = Math.ceil(e.value * 100);
    }
    return e;
  });

  if (item.type === "0" || item.type === "2") {
    form.value.rangDate = [`${details.work[0]} ${item.start}`, `${details.work[1]} ${item.stop}`];
    // form.value.rangDate = [item.start, item.stop];
  } else if (item.type === "3") {
    form.value.work = details.work;
  }
};

const add = () => {
  resetForm();
  form.value.visible = true;
};
const filterChange = (dataIndex: string, filteredValues: string[]) => {
  if (dataIndex === "resolutionDesc") {
    dataIndex = "resolutionId";
  }

  query.value[dataIndex] = filteredValues[0];
  getList();
};
const pageSizeChange = (size: number) => {
  query.value.pageSize = size;
  getList();
};

const search = () => {
  query.value.pageNum = 1;
  getList();
};

const deleteItem = async (id?: string) => {
  const ids = id ? [id] : selectedKeys.value;
  await delJobs(ids);
};
</script>

<style lang="scss" scoped></style>
